from django_redis import get_redis_connection
from drf_haystack.serializers import HaystackSerializer
from rest_framework import serializers

from goods.models import SKU
from goods.search_indexes import SKUIndex


class SKUsSerializer(serializers.ModelSerializer):
    class Meta:
        model = SKU
        fields = "__all__"


class SKUIndexSerializer(HaystackSerializer):
    """
    SKU索引结果数据序列化器
    """
    object = SKUsSerializer(read_only=True)

    class Meta:
        index_classes = [SKUIndex]
        fields = ('text', 'object')


class SKUHistorySerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(min_value=0)

    def validate(self, attrs):
        try:
            SKU.objects.get(id=attrs['sku_id'])
        except:
            raise serializers.ValidationError("商品不存在")

        return attrs


    def create(self, validated_data):
        user = self.context['request'].user
        sku_id = validated_data['sku_id']
        conn = get_redis_connection("history")

        conn.lrem("history_%s" %user.id,0,sku_id)

        conn.lpush("history_%s" %user.id,sku_id)

        conn.ltrim("history_%s" %user.id,0,4)

        return validated_data
